package com.lds.erp.order.mch;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.dph.common.utils.base.PageEntity;
import com.dph.common.utils.core.exception.BizError;
import com.dph.common.utils.enums.Status;


import com.dph.common.utils.service.Base;
import com.dph.common.utils.service.BaseResult;
import com.lds.erp.mch.mch.MchInfoFacade;
import com.lds.erp.mch.mch.order.*;
import com.lds.erp.mch.mch.result.*;
import com.lds.erp.mch.mch.vo.MchInfoPageAO;
import com.lds.erp.mch.mch.vo.MchInfoPageVO;
import com.lds.erp.order.OrderOrderClient;
import com.lds.erp.order.mch.ao.*;
import com.lds.erp.order.mch.vo.*;
import com.lds.erp.order.order.order.OrderSendTimeOrder;
import com.lds.erp.order.order.result.OrderSendTimeResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dph.common.utils.utils.AppUtils;
import com.lds.erp.base.JsonResult;
import com.lds.erp.common.YNEnum;
import com.lds.erp.common.util.AccountCache;
import com.lds.erp.common.util.AccountUtils;
import com.lds.erp.mch.formid.MchWeixinFormFacade;
import com.lds.erp.mch.formid.order.MchFormAddOrder;
import com.lds.erp.mch.formid.result.MchFormAddResult;
import com.lds.erp.mch.mch.MchAddressFacade;
import com.lds.erp.order.mch.info.MchInfo;
import com.lds.erp.util.JsonUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping(value = "/api/order/mchinfo/")
@Api(value = "商户收货地址", description = "商户收货地址", tags = {"商户收货地址"})
public class MchInfoController {

    private Logger logger = LoggerFactory.getLogger(MchInfoController.class);

    @Reference(version = "1.0")
    private MchAddressFacade mchAddressFacade;

    @Reference(version = "1.0")
    private MchWeixinFormFacade mchWeixinFormFacade;


    @Reference(version = "1.0")
    private MchInfoFacade mchInfoFacade;


    @Autowired
    private OrderOrderClient orderOrderClient;

    @GetMapping(value = "mchAddress")
    @ApiOperation(value = "获取商户默认收货地址接口(senilon)", notes = "获取商户默认收货地址接口")
    public JsonResult<MchInfoVO> mchAddress(Integer mchChooseDistrictId, Integer agent, String mchId) {
        // 模型转换
        MchAddressQueryOrder order = new MchAddressQueryOrder();
        MchAddressDefaultResult checkresult = new MchAddressDefaultResult();
        if (agent != null && agent == 1) {
            if (mchId != null) {
                order.setMchId(mchId);
            } else {
                JsonUtils.fail("代理下单客户id不能为空");
            }
        } else {
            AccountCache accountCache = AccountUtils.getAccount();
            order.setMchId(accountCache.getMchId());
        }

        order.setSerialNo(AppUtils.newNo());
        order.setMchDefaultAddress(YNEnum.Y);
        order.setMchChooseDistrictId(mchChooseDistrictId);
        logger.info("######## MchInfoController.mchAddress mchChooseDistrictId={}", order.getMchChooseDistrictId());
        MchAddressDefaultResult result = mchAddressFacade.findMchDefaultAddressByMchId(order);
        logger.info("默认地址信息result={}", result);

        Integer mchDistrictId = null;

        if (result.getMchInfo() != null) {
            mchDistrictId = result.getMchInfo().getMchDistrictId();
        }

        if (mchDistrictId == null || mchChooseDistrictId == null) {
            result.setCode("0");
            result.setStatus(Status.FAIL);
            result.setMessage("选择区和收货地址区都必须填写");
        }

        if (mchDistrictId == null) {
            MchAddressDefaultResult resultNoMch = new MchAddressDefaultResult();
            resultNoMch.setCode("0");
            resultNoMch.setStatus(Status.FAIL);
            resultNoMch.setMessage("没有获取到用户默认地址的区域");

            return JsonUtils.fail(resultNoMch, MchInfoVO.class);
        }


        Integer areacheck = mchInfoFacade.checkSameArea(mchDistrictId, mchChooseDistrictId);
        // 屏蔽需求有变化
//		if (mchDistrictId.intValue()  !=  mchChooseDistrictId.intValue())
//		{
//			result.setCode("0");
//			result.setStatus(Status.FAIL);
//			result.setMessage("您的收货地址与绑定区域不一致，请您修改收货地址或联系销售处理");
//			// 不用在显示下面的数据
//			areacheck=1;
//		}

        if (areacheck != 1) {
            if (areacheck == -1) {
                result.setCode("0");
                result.setStatus(Status.FAIL);
                result.setMessage("选择区和收货地址区都必须填写");
            } else if (areacheck == -2) {
                result.setCode("0");
                result.setStatus(Status.FAIL);
                result.setMessage("选择区和收货地址区没有匹配到仓库");
            } else if (areacheck == -3) {
                result.setCode("0");
                result.setStatus(Status.FAIL);
                result.setMessage("选择区和收货地址区没有匹配到同一个仓库");
            }

        }

        if (result != null && result.getMchInfo() != null && result.getMchInfo().getMchDistrictId() != null) {

            OrderSendTimeOrder sendTimeOrder = new OrderSendTimeOrder();
            sendTimeOrder.setSerialNo(AppUtils.newNo());
            sendTimeOrder.setDistrictId(result.getMchInfo().getMchDistrictId());
            sendTimeOrder.setMchId(order.getMchId());
            OrderSendTimeResult sendTimeResult = orderOrderClient.orderSendTime(sendTimeOrder);
            if (sendTimeResult != null) {
                result.setSendTimeResult(sendTimeResult);
            }

        }
        logger.info("######## MchInfoController.mchAddress result.getMchInfo().getWarehouseId(2)={}", result.getMchInfo().getWarehouseId());
        logger.info("######## MchInfoController.mchAddress result.getMchInfo().getWarehouseId(2)={}", result.getMchInfo().getWarehouseName());
        return result.isSuccess() ? JsonUtils.success(result, MchInfoVO.class) : JsonUtils.fail(result, MchInfoVO.class);
    }

    @GetMapping(value = "mchAddressList")
    @ApiOperation(value = "获取商户收货地址列表(senilon)", notes = "获取商户收货地址列表,可能有多个地址")
    public JsonResult<MchAddressQueryVo> mchAddressList(Integer agent, String mchId) {
        // 模型转换
        MchAddressQueryOrder order = new MchAddressQueryOrder();
        order.setSerialNo(AppUtils.newNo());

        if (agent != null && agent == 1) {
            if (mchId != null) {
                order.setMchId(mchId);
            } else {
                JsonUtils.fail("代理下单客户id不能为空");
            }
        } else {
            AccountCache accountCache = AccountUtils.getAccount();
            order.setMchId(accountCache.getMchId());
        }


        MchAddressQueryResult result = mchAddressFacade.findMchAddressByMchId(order);
        return result.isSuccess() ? JsonUtils.success(result, MchAddressQueryVo.class)
                : JsonUtils.fail(result.getMessage());
    }

    @PostMapping(value = "editAddress")
    @ApiOperation(value = "更新商户收货地址接口(senilon)", notes = "更新商户收货地址接口")
    public JsonResult<MchInfoVO> editAddress(@RequestBody MchInfoUpdateAO ao) {

        if (ao.getMchStreet() != null && ao.getMchStreet().equalsIgnoreCase("暂不选择")) {
            ao.setMchStreet("");
        }


        MchAddressEditOrder order = new MchAddressEditOrder();
        order.setSerialNo(AppUtils.newNo());
        BeanUtils.copyProperties(ao, order);

        if (ao.getAgent() != null && ao.getAgent() == 1) {
            if (ao.getMchId() != null) {
                order.setMchId(ao.getMchId());
            } else {
                JsonUtils.fail("代理下单客户id不能为空");
            }
        } else {
            AccountCache accountCache = AccountUtils.getAccount();
            order.setMchId(accountCache.getMchId());
        }


        MchAddressEditResult result = mchAddressFacade.editMchAddress(order);

        MchInfoVO vo = new MchInfoVO();
        MchInfo mchInfo = new MchInfo();
        vo.setMchInfo(mchInfo);
        BeanUtils.copyProperties(ao, mchInfo);
        mchInfo.setMchId(order.getMchId());

        return result.isSuccess() ? JsonUtils.success(vo) : JsonUtils.fail(result.getMessage());
    }

    @PostMapping("addFromId")
    @ApiOperation(value = "微信测试连接（提交fromid过来）", notes = "微信测试连接（提交fromid过来）")
    public JsonResult addFromId(@RequestBody WXFromIdAO ao) {
        logger.info("WXFromIdAO formId={}", ao.getFromId());
        MchFormAddOrder order = new MchFormAddOrder();
        order.setSerialNo(AppUtils.newNo());
        order.setMchFormid(ao.getFromId());
        AccountCache accountCache = AccountUtils.getAccount();
        if (null == accountCache) {
            return JsonUtils.success("addFromId用户不存在");
        }
        order.setMchId(accountCache.getMchId());
        MchFormAddResult result = mchWeixinFormFacade.addMchFormid(order);
        // 不在乎结果，每次都返回成功就可以
        return JsonUtils.success("操作成功");
    }

    @GetMapping(value = "findMchInfoByMobile")
    @ApiOperation(value = "获取商户", notes = "获取商户")
    public JsonResult<MchInfoResult> findMchInfoByMobile(@RequestBody MchInfoByMchMobileOrder order) {
        MchInfoResult result = mchInfoFacade.findMchInfoByMobileNew(order);
        return result.getMchInfo().getMchId() != null ? JsonUtils.success(result, MchInfoResult.class)
                : JsonUtils.fail(result.getMessage());
    }

    @GetMapping(value = "findMchInfoByPage")
    @ApiOperation(value = "商户列表(senilon)")
    public JsonResult<MchInfoPageVO> findMchInfoByPage(MchInfoPageAO ao, HttpServletRequest request,
                                                       HttpServletResponse response) {
        MchInfoPageOrder order = new MchInfoPageOrder();
        BeanUtils.copyProperties(ao, order);
        // 分页设置
        if (null == ao.getPageNum()) {
            ao.setPageNum(1);
        }
        if (null == ao.getPageSize()) {
            ao.setPageSize(10);
        }
        order.setPage(new PageEntity(ao.getPageNum(), ao.getPageSize()));
        MchInfoPageResult result = mchInfoFacade.findMchInfoByPage(order);
        return result.isSuccess() ? JsonUtils.success(result, MchInfoPageVO.class)
                : JsonUtils.fail(result.getMessage());

    }

    /**
     * 查询用户积分明细
     *
     * @param ao
     * @return
     */
    @GetMapping("getMchPointsDetail")
    public JsonResult<MchPointsDetailPageVO> getMchPointsDetail(MchPointsDetailPageAO ao) {
        MchPointsDetailPageOrder order = new MchPointsDetailPageOrder();
        BeanUtils.copyProperties(ao, order);
        order.setMchId(ao.getMchId());
        order.setPage(new PageEntity(ao.getPageNum(), ao.getPageSize()));
        MchMemberPointsDetalResult result = mchInfoFacade.getMchMemberPointsDetailByID(order);
        return result.isSuccess() ? JsonUtils.success(result, MchPointsDetailPageVO.class)
                : JsonUtils.fail(result.getMessage());
    }

    /**
     * 会员信息
     *
     * @param ao
     * @return
     */
    @GetMapping("hyPayInfo")
    public JsonResult<MchOpenInfoVO> hyPayInfo(HyInfoAO ao) {
        MchHyOpenRecordOrder order = new MchHyOpenRecordOrder();
        order.setMchId(ao.getMchId());
        order.setSerialNo(AppUtils.newNo());
        MchHyOpenRecordResult result = mchInfoFacade.hyOpenInfo(order);
        return result.isSuccess() ? JsonUtils.success(result, MchOpenInfoVO.class)
                : JsonUtils.fail(result.getMessage());
    }

    /**
     * 开通会员
     *
     * @param ao
     * @return
     */
    @GetMapping("hyOpen")
    public JsonResult<MchHyPayInfoVO> hyPay(HyInfoAO ao) {
        MchHyPayOrder order = new MchHyPayOrder();
        order.setMchId(ao.getMchId());
        order.setSerialNo(AppUtils.newNo());
        MchHyPayResult result = mchInfoFacade.hyOpenPay(order);
        return result.isSuccess() ? JsonUtils.success(result, MchHyPayInfoVO.class)
                : JsonUtils.fail(result.getMessage());
    }


    @PostMapping(value = "updateMchInfo")
    @ApiOperation(value = "更新商户呢称和头像", notes = "更新商户呢称和头像接口")
    public JsonResult updateMchInfo(@RequestBody UpdateMchInfoAO ao) {
        MchInfoOrder order = new MchInfoOrder();
        AccountCache accountCache = AccountUtils.getAccount();
        order.setMchId(accountCache.getMchId());
        order.setSerialNo(AppUtils.newNo());
        order.setMchImage(ao.getMchImage());
        order.setMchName(ao.getMchName());
        BaseResult result = mchInfoFacade.updateMchInfo(order);
        return JsonUtils.success("操作成功");
    }
}
